package com.xj.nrpc.core.media;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xj.nrpc.core.handler.param.ServerRequest;
import com.xj.nrpc.core.util.DataUtil;
import com.xj.nrpc.core.util.ResponseEntity;

public class Media {

	public static final Map<String, BeanMethod> media_map = new ConcurrentHashMap<String, BeanMethod>();

	private static volatile Media media = null;

	private Media() {
	}

	public static Media newInstance() {
		if (media == null) {
			synchronized (Media.class) {
				if (media == null) {
					media = new Media();
				}
			}
		}
		return media;
	}

	public ResponseEntity process(ServerRequest req) {
		BeanMethod bean = media_map.get(req.getCommond());
		Object obj = req.getData();
		ResponseEntity resp = null;
		if (bean != null) {
			Object beanName = bean.getBean();
			Method method = bean.getMethod();
			if (method == null) {
				return null;
			}
			Class<?>[] types = method.getParameterTypes();
			JSONArray array = null;
			if (DataUtil.isArray(obj)) {
				array = JSONObject.parseArray(obj.toString());
			}
			Object o = null;
			Object[] list = new Object[types.length];
			for (int i = 0; i < types.length; i++) {
				Class<?> c = types[i];
				if (array == null) {
					o = obj;
				} else {
					if (array.size() < i) {
						continue;
					}
					o = array.get(i);
				}
				Object args = JSONObject.parseObject(JSONObject.toJSONString(o), c);
				list[i] = args;
			}
			try {
				resp = (ResponseEntity) method.invoke(beanName, list);
			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				e.printStackTrace();
			}
		}

		return resp;
	}
}
